#!/usr/bin/env bash
#
# Explicitly switches the relative submodules locations on GitHub to the original public URLs
#
#       '../../group/repo.git' to 'https://github.com/group/repo.git'
#
# This can be useful for non-GitHub forks to automate getting of right submodules sources.
#

#
# It makes sense to do
#
#       git submodule deinit --force .
#       git submodule init
#
# before running this, and
#
#       git submodule update --recursive
#
# after that. These were not included over this script deliberately, to use the script flexibly
#

set -o errexit
set -o pipefail
set -o nounset

DEBUG_SHELL=${DEBUG_SHELL:-"0"}
[ "${DEBUG_SHELL}" = "1" ] && set -x

# GIT_SERVER_ADDR="https://github.com"
# GIT_SERVER_ADDR="https://gitee.com"
# GIT_SERVER_ADDR="https://hub.fastgit.xyz"
GIT_SERVER_ADDR="https://cors.zme.ink/https://github.com"
### '../../' relative locations
SUBURL="${GIT_SERVER_ADDR}/"
if [ -d $1 ] ; then
    echo $SUBURL $1
    cd $1
else
    echo "please check \"$1\" is a github dir?"
    exit
fi


if [ $# -lt 2  ] ; then
    echo "http set to replace to $SUBURL"
    for LINE in $(git config -f .gitmodules --list | grep "\.url=http[^.]")
    do
        # echo "${LINE}"
        # SUBPATH=$(echo "${LINE}" | grep  "^submodule.*.url=http")
        SUBPATH=$(echo "${LINE}" | sed 's|^submodule\.\(.*\)\.url=http.*|\1|')
        # echo "SUBPATH $SUBPATH"
        LOCATION=$(echo "${LINE}" | sed 's|.*\.url=.*github\.com/\(.*\)$|\1|')
        # echo "LOCATION $LOCATION"
        SUBURL="${GIT_SERVER_ADDR}/$LOCATION"
        # echo "SUBURL $SUBURL"
        # echo "submodule.${SUBPATH}.url"
        git config submodule."${SUBPATH}".url "${SUBURL}"
        # echo "git config submodule.${SUBPATH}.url ${SUBURL}"
    done
elif [ "$2" == "esp" ] ; then
    echo "esp set to replace to $SUBURL"
    for LINE in $(git config -f .gitmodules --list | grep "\.url=../../[^.]")     #esp32
    do
        # echo "${LINE}"
        SUBPATH=$(echo "${LINE}" | sed "s|^submodule\.\([^.]*\)\.url.*$|\1|")
        # echo $SUBPATH
        LOCATION=$(echo "${LINE}" | sed 's|.*\.url=\.\./\.\./\(.*\)$|\1|')
        # echo $LOCATION
        SUBURL="${GIT_SERVER_ADDR}/$LOCATION"
        # echo $SUBURL

        git config submodule."${SUBPATH}".url "${SUBURL}"
    done
else
    return 1
fi



echo "last change as follow:"
git config --get-regexp '^submodule\..*\.url$'

